﻿using System;
using System.Windows.Controls;
using System.Windows;
using System.Collections.ObjectModel;
using System.IO;
using Newtonsoft.Json;
using PenguinPublishNS.Models;
using Microsoft.WebMatrix.Extensibility;

namespace PenguinPublishNS.Views
{
    /// <summary>
    /// Interaction logic for Options.xaml
    /// </summary>
    public partial class SetOptions : UserControl
    {
        private ObservableCollection<Options> myOptions;
        private string optionsFile;
        protected IWebMatrixHost host;

        public SetOptions()
        {
            InitializeComponent();
            if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                txtNetConn.Text = "FYI: No Network Connection";
            }
            // check for our settings file in case this is first time extension has been used
            // TBD: should be there already because we create it and check for it in WebMatrixExtension.Initialize()
            string optionsPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Webmatrix PenguinPublish";
            optionsFile = optionsPath + @"\pPubOptions.json";
            if (!Directory.Exists(optionsFile))
                Directory.CreateDirectory(optionsPath);
            if (!File.Exists(optionsFile))
            {
                // make a .json file to store the options. Initialize with all false values
                // to make a proper json 'array' surround with []. Otherwise cannot deserialize to ObservableCollection
                FileStream tempFile = File.Create(optionsFile);
                tempFile.Close();

                Options newOptions = new Options { extLogging = false, pubNoPreview = false, showValidateResults = false, alwaysUsePPK = false, startOver = false };
                string json = JsonConvert.SerializeObject(newOptions, Formatting.Indented);
                File.WriteAllText(optionsFile, "[" + json + "]");

            }

            var streamR2 = new StreamReader(optionsFile);
            myOptions = JsonConvert.DeserializeObject<ObservableCollection<Options>>(streamR2.ReadToEnd());

            this.DataContext = myOptions;
        }

        private void btnSave_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            string json = JsonConvert.SerializeObject(myOptions, Formatting.Indented);
            File.WriteAllText(optionsFile, json);
        }

        private void UserControl_Unloaded_1(object sender, RoutedEventArgs e)
        {
            //MessageBox.Show("This is unloading");
            // this seems reliable, will call Save here
            // var myCtl = (UserControl)sender;  but not finding a way to detect cancel/save buttons

            string json = JsonConvert.SerializeObject(myOptions, Formatting.Indented);
            File.WriteAllText(optionsFile, json);
        }
    }
}
